<template>
  <div class="app-container">
    <div class="filter-condition">
      <label>条件搜索</label>
      <el-form
        size="mini"
        :inline="true"
        class="mini-form"
        style="flex: 1"
        :model="temp"
        @submit.native.prevent
      >
        <el-col :span="4">
          <el-form-item>
            <el-input
              v-model="temp.market_name"
              placeholder="名称"
              prefix-icon="el-icon-search"
              clearable
              @change="getPageData"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-date-picker
              v-model="temp.dateOrderRange"
              value-format="yyyy-MM-dd"
              size="mini"
              type="daterange"
              align="center"
              range-separator="-"
              start-placeholder="交易开始"
              end-placeholder="交易结束"
              :picker-options="pickerOptions"
              style="width: 250px"
              @change="getPageData"
            />
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <el-row>
      <el-col :span="2">
        <label class="row-label">业务操作</label>
      </el-col>
      <el-col :span="22" class="align-right">
        <el-button-group>
          <el-button
            type="primary"
            icon="el-icon-connection"
            @click="handleSyncButton"
          >
            {{ $t('table.sync') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            class="refresh-button"
            @click="handleRefresh"
          >
            {{ $t('table.refresh') }}
          </el-button>
        </el-button-group>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%;"
      :height="commonLayoutHeight"
    >
      <el-table-column prop="image" label="图片" width="300" class-name="image">
        <template slot-scope="scope">
          <img :src="scope.row.image" alt="图片" style="width:100px;height:100px">
        </template>
      </el-table-column>
      <el-table-column prop="market_name" label="名称">
        <template slot-scope="scope">
          <p>{{ scope.row.market_name }}</p>
          <p>{{ scope.row.type }}</p>
        </template>
      </el-table-column>
      <el-table-column
        prop="date"
        label="交易日期"
      />
      <el-table-column
        prop="price"
        label="交易价格"
      />
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10,50,100,200,500,1000]"
      :page-size="pageSize"
      :total="totalItems"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <ly-dialog
      v-model="visible"
      title="交易同步"
      width="750px"
      top="10vh"
      :modal="true"
      :modal-append-to-body="false"
      :show-confirm-cancel-button="false"
      :before-close="handleCancel"
    >
      <template #operation>
        <el-button
          type="primary"
          icon="el-icon-circle-check"
          :loading="syncLoading"
          @click="handleConfirm"
        >
          {{ $t('table.sync') }}
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-delete"
          class="deleted-button"
          @click="handleClear"
        >
          清空
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-close"
          class="pause-button"
          @click="handleCancel"
        >
          {{ $t('table.cancel') }}
        </el-button>
      </template>
      <ly-form
        ref="form"
        size="mini"
        label-width="120px"
        :model="temp"
        :rules="rules"
      >
        <el-row>
          <el-col :span="20">
            <el-form-item
              label="STEAM"
              prop="Cookie"
            >
              <el-input
                v-model="temp.Cookie"
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 200}"
                placeholder="请输入cookie"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </ly-form>
    </ly-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getList, updateOne } from '@/api/moveBrick'

export default {
  name: 'SteamWarehouse',
  data() {
    return {
      columns: [
        {
          headerName: '饰品名',
          field: 'name'
        },
        {
          headerName: 'buff链接',
          field: 'buff_url'
        },
        {
          headerName: 'steam链接',
          field: 'steam_url'
        },
        {
          headerName: 'buff在售数量',
          field: 'buff_sell_num'
        },
        {
          headerName: 'buff在售价格',
          field: 'buff_sell_min_price'
        },
        {
          headerName: 'steam求购价',
          field: 'steam_buy_max_price',
          showSummary: true
        },
        {
          headerName: 'steam在售价格',
          field: 'steam_sell_min_price',
          showSummary: true
        },
        {
          headerName: '预计利润',
          field: 'buffPrice',
          showSummary: true
        },
        {
          headerName: '预计利润率',
          field: 'profit_rate',
          showSummary: true
        },
        {
          headerName: '获取时间',
          field: 'time'
        }
      ],
      rowData: {},
      temp: {
        Cookie: '',
        market_name: '',
        dateOrderRange: [],
        beginDate: '',
        endDate: ''
      },
      resetTemp: {
        Cookie: '',
        market_name: '',
        dateOrderRange: [],
        beginDate: '',
        endDate: ''
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      rules: {
        // dateOrderRange: [{ validator: validate, required: true, message: ' ', trigger: 'change' }]
      },
      tableData: [],
      html: '',
      currentPage: 1,
      pageSize: 50,
      totalItems: 0,
      jsons: {},
      timer: null,
      visible: false,
      loading: false,
      syncLoading: false
    }
  },
  computed: {
    ...mapState('app', {
      commonLayoutHeight: state => state.height.clientHeight - 265
    })
  },
  created() {
    this.getPageData()
  },
  mounted() {
    if (localStorage.getItem('Cookie')) {
      this.temp.Cookie = localStorage.getItem('Cookie')
    }
    this.totalItems = this.tableData.length
  },
  methods: {
    // 同步
    handleSyncButton() {
      this.visible = true
    },
    handleConfirm() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.syncLoading = true
          const params = {
            Cookie: this.temp.Cookie
          }
          window.localStorage.setItem('Cookie', this.temp.Cookie)
          const result = await updateOne('getSyncDeal', params)
          if (result.code === 200) {
            this.$notify({
              title: '成功',
              message: '同步成功',
              type: 'success',
              duration: 2000
            })
            this.syncLoading = false
            this.visible = false
            setTimeout(() => {
              this.handleRefresh()
            }, 300)
          }
        } else {
          this.$alert('有必选项未填', '警告', {
            confirmButtonText: '确定'
          })
          return false
        }
      })
    },
    // 清空
    handleClear() {
      this.syncLoading = false
      this.temp = Object.assign({}, this.resetTemp)
      window.localStorage.setItem('Cookie', this.temp.Cookie)
    },
    // 关闭
    handleCancel() {
      this.syncLoading = false
      this.visible = false
    },
    // 表格数据
    async getPageData() {
      this.loading = true
      const params = Object.assign({}, this.temp)
      if (params.dateOrderRange) {
        params.beginDate = params.dateOrderRange[0]
        params.endDate = params.dateOrderRange[1]
      }
      params.page = this.currentPage
      params.pageSize = this.pageSize
      delete params.Cookie
      delete params.dateOrderRange
      const result = await getList('getTransaction', params)
      if (result.code === 200) {
        this.tableData = result.data.pageItems
        this.totalItems = result.data.total
        this.loading = false
      }
    },
    // 刷新
    handleRefresh() {
      this.getPageData()
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.currentPage = 1 // 切换每页显示数量时，重置当前页为第一页
      this.handleRefresh()
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.handleRefresh()
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table__cell{
  text-align: center;
}
::v-deep .el-table__header{
  font-size: 14px
}
::v-deep .el-table__row{
  font-size: 16px
}
::v-deep .el-pagination{
 background-color: #fff;
 height: 40px;
 display: flex;
 align-items: center;
 flex-direction: row;
 justify-content: flex-end;
 padding-right: 20px;
}
</style>
